<template>
  <div style="margin:20px">
    <el-form :inline="true" :model="searchRecord" :rules="searchRules" class="demo-form-inline">
      <el-form-item label="登录名" prop="username">
        <el-input v-model="searchRecord.username" placeholder="登录名" />
      </el-form-item>
      <el-form-item label="姓名" prop="realName">
        <el-input v-model="searchRecord.realName" placeholder="姓名" />
      </el-form-item>
      <el-form-item label="电话" prop="phone">
        <el-input v-model="searchRecord.phone" placeholder="电话" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="searchRecord.email" placeholder="邮箱" />
      </el-form-item>
      <el-form-item label="是否锁定" prop="locked">
        <el-select v-model="searchRecord.locked" placeholder="是否锁定">
          <el-option label="未锁定" :value="0" />
          <el-option label="锁定" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="getList">查询</el-button>
      </el-form-item>
    </el-form>

    <el-row style="margin-bottom: 10px">
      <el-button type="primary" size="small" @click="create">新增</el-button>
      <el-button type="primary" size="small" @click="bathDelete">批量删除</el-button>
      <!--      <el-button type="primary" size="small" @click="templateDown">模板</el-button>-->
      <!--      <el-button type="primary" size="small" @click="importData">导入</el-button>-->
      <!--      <el-button type="primary" size="small" @click="exportData">导出</el-button>-->
    </el-row>
    <el-row>
      <el-table
        ref="mainTable"
        :data="tableData"
        :stripe="true"
        :border="true"
        :highlight-current-row="true"
        style="width: 100%"
        @select="tableSelect"
        @selection-change="tableSelectionChange"
      >
        <el-table-column type="selection" align="center" width="55" />
        <el-table-column prop="userId" label="用户ID" align="center" width="180" />
        <el-table-column prop="username" label="用户名" align="center" width="180" />
        <el-table-column prop="realName" label="姓名" align="center" width="180" />
        <el-table-column prop="phone" label="电话" align="center" width="180" />
        <el-table-column prop="email" label="邮箱" align="center" width="180" />
        <el-table-column label="性别" align="center" width="180">
          <template v-slot:default="scope">
            <span v-if="scope.row.sex === 0">男</span>
            <span v-if="scope.row.sex === 1">女</span>
          </template>
        </el-table-column>
        <el-table-column label="是否锁定" align="center" width="180">
          <template v-slot:default="scope">
            <span v-if="scope.row.locked === 0">未锁定</span>
            <span v-if="scope.row.locked === 1">锁定</span>
          </template>
        </el-table-column>
        <el-table-column label="最后登录时间" align="center" width="180">
          <template v-slot:default="scope">
            <span>{{ scope.row.lastTime }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center" width="150">
          <template v-slot:default="scope">
            <el-button type="text" size="small" @click="query(scope.row)">查看</el-button>
            <el-button type="text" size="small" @click="edit(scope.row)">编辑</el-button>
            <el-button type="text" size="small" @click="remove(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 10px"
        :current-page="page.currentPage"
        :layout="$store.state.page.layout"
        :page-sizes="$store.state.page.pageSizes"
        :page-size="page.pageSize"
        :total="page.total"
        @size-change="pageSizesChange"
        @current-change="currentPageChange"
      />
    </el-row>
    <!--    新建 -->
    <el-dialog ref="createDialog" :visible.sync="createDialog.visible" title="新增" width="30%" :before-close="done=>done()">
      <!--      <template v-slot:title class="dialog-title">-->
      <!--        <span>这是一段信息</span>-->
      <!--      </template>-->
      <template slot>
        <el-form ref="createDialogForm" :model="createRecord" :rules="createRules" label-width="80px" label-position="right">
          <el-form-item label="登录名" prop="username">
            <el-input v-model="createRecord.username" placeholder="登录名" />
          </el-form-item>
          <el-form-item label="密码" prop="username">
            <el-input v-model="createRecord.password" placeholder="密码" />
          </el-form-item>
          <el-form-item label="姓名" prop="realName">
            <el-input v-model="createRecord.realName" placeholder="姓名" />
          </el-form-item>
          <el-form-item label="电话" prop="phone">
            <el-input v-model="createRecord.phone" placeholder="电话" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="createRecord.email" placeholder="邮箱" />
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-radio v-model="createRecord.sex" :label="0">男</el-radio>
            <el-radio v-model="createRecord.sex" :label="1">女</el-radio>
          </el-form-item>
          <el-form-item label="是否锁定" prop="locked">
            <el-radio v-model="createRecord.locked" :label="0">未锁定</el-radio>
            <el-radio v-model="createRecord.locked" :label="1">锁定</el-radio>
          </el-form-item>
        </el-form>
      </template>
      <template slot="footer" class="dialog-footer">
        <el-button @click="createDialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="createDialogSave">确 定</el-button>
      </template>
    </el-dialog>
    <!--    修改 -->
    <el-dialog ref="editDialog" :visible.sync="editDialog.visible" title="编辑" width="40%" :before-close="done=>done()">
      <template v-slot:default class="dialog-title">
        <el-tabs v-model="editTabsActive" @tab-click="tabClick">
          <el-tab-pane label="基本信息编辑" name="first">
            <el-form ref="editDialogForm" :model="editRecord" :rules="editRules" label-width="80px" label-position="right">
              <el-form-item label="登录名" prop="username">
                <el-input v-model="editRecord.username" placeholder="登录名" />
              </el-form-item>
              <el-form-item label="密码" prop="username">
                <el-input v-model="editRecord.password" placeholder="密码" />
              </el-form-item>
              <el-form-item label="姓名" prop="realName">
                <el-input v-model="editRecord.realName" placeholder="姓名" />
              </el-form-item>
              <el-form-item label="电话" prop="phone">
                <el-input v-model="editRecord.phone" placeholder="电话" />
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="editRecord.email" placeholder="邮箱" />
              </el-form-item>
              <el-form-item label="性别" prop="sex">
                <el-radio v-model="editRecord.sex" :label="0">男</el-radio>
                <el-radio v-model="editRecord.sex" :label="1">女</el-radio>
              </el-form-item>
              <el-form-item label="是否锁定" prop="locked">
                <el-radio v-model="editRecord.locked" :label="0">未锁定</el-radio>
                <el-radio v-model="editRecord.locked" :label="1">锁定</el-radio>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="角色分配" name="second">
            <el-table
              ref="roleTable"
              :data="roleTableData"
              :stripe="true"
              :border="true"
              :highlight-current-row="true"
              style="width: 100%"
              @selection-change="roleTableSelectionChange"
            >
              <el-table-column type="selection" align="center" width="55" />
              <el-table-column prop="roleId" label="角色ID" align="center" />
              <el-table-column prop="roleName" label="角色名称" align="center" />
              <el-table-column prop="roleCode" label="角色编码" align="center" />
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </template>
      <template v-slot:footer class="dialog-footer">
        <el-button @click="editDialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="editDialogSave">确 定</el-button>
      </template>
    </el-dialog>
    <!--  查看 -->
    <el-dialog ref="queryDialog" :visible.sync="queryDialog.visible" title="查看" width="30%" :before-close="done=>done()">
      <template v-slot:default class="dialog-title">
        <el-form :model="queryRecord" label-width="80px" label-position="right">
          <el-form-item label="登录名" prop="username">
            <el-input v-model="queryRecord.username" placeholder="登录名" :readonly="true" />
          </el-form-item>
          <!--          <el-form-item label="密码" prop="username">-->
          <!--            <el-input v-model="editRecord.password" placeholder="密码" :readonly="true"/>-->
          <!--          </el-form-item>-->
          <el-form-item label="姓名" prop="realName">
            <el-input v-model="queryRecord.realName" placeholder="姓名" :readonly="true" />
          </el-form-item>
          <el-form-item label="电话" prop="phone">
            <el-input v-model="queryRecord.phone" placeholder="电话" :readonly="true" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="queryRecord.email" placeholder="邮箱" :readonly="true" />
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-radio v-model="queryRecord.sex" :label="0" :disabled="true">男</el-radio>
            <el-radio v-model="queryRecord.sex" :label="1" :disabled="true">女</el-radio>
          </el-form-item>
          <el-form-item label="是否锁定" prop="locked">
            <el-radio v-model="queryRecord.locked" :label="0" :disabled="true">未锁定</el-radio>
            <el-radio v-model="queryRecord.locked" :label="1" :disabled="true">锁定</el-radio>
          </el-form-item>
        </el-form>

      </template>
    </el-dialog>

  </div>
</template>

<script>

import { page, create, edit, deleteByIds, assignRole } from '@/api/user.js'
import { findAll } from '@/api/role'
import { removeEmptyString } from '@/utils/function'
import { Message } from '_element-ui@2.13.2@element-ui'
export default {
  name: 'User',
  data() {
    return {
      // 搜索表单
      searchRecord: {
        username: '',
        realName: '',
        phone: '',
        email: '',
        locked: 0
      },
      searchRules: {
        username: [{ trigger: 'blur' }],
        realName: [{ trigger: 'blur' }],
        phone: [{ trigger: 'blur' }],
        email: [{ trigger: 'blur' }],
        locked: [{ trigger: 'blur' }]
      },
      tableData: null, // 表格数据
      // 分页参数
      page: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      tableSelection: [],
      createDialog: {
        visible: false
      },
      editDialog: {
        visible: false
      },
      queryDialog: {
        visible: false
      },
      createRecord: {
        username: '',
        password: '',
        realName: '',
        phone: '',
        email: '',
        sex: 0,
        locked: 0
      },
      createRules: {
        username: [{ type: 'string', required: true, message: '用户名是必填项,且长度小于', trigger: 'blur' }],
        password: [{ type: 'string', required: true, message: '密码是必填项', trigger: 'blur' }],
        realName: [{ type: 'string', message: '姓名是可选项', trigger: 'blur' }],
        phone: [{ type: 'string', message: '用户名是必填项', trigger: 'blur' }],
        email: [{ type: 'email', message: '不是合法的邮箱', trigger: 'blur' }]
      },
      editTabsActive: 'first',
      editRecord: {
        username: '',
        password: '',
        realName: '',
        phone: '',
        email: '',
        sex: 0,
        locked: 0
      },
      editRules: {
        username: [{ type: 'string', message: '用户名是必填项,且长度小于', trigger: 'blur' }],
        password: [{ type: 'string', message: '密码是必填项', trigger: 'blur' }],
        realName: [{ type: 'string', message: '姓名是可选项', trigger: 'blur' }],
        phone: [{ type: 'string', message: '用户名是必填项', trigger: 'blur' }],
        email: [{ type: 'email', message: '不是合法的邮箱', trigger: 'blur' }]
      },
      roleTableData: [],
      roleTableSelection: [],
      queryRecord: {}

    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 表单校验函数
    validatorForm(rule, value, callback) {
      if (value === undefined || value === null || value === '' || value.replace(/' '/g, '') === '') {
        this.searchRecord[rule.username] = null
      } else {
        callback(new Error('错误'))
      }
    },
    tableSelect(selection, row) {
      // this.tableSelection = selection
    },
    tableSelectionChange(selection) {
      this.tableSelection = selection
    },
    // 渲染表格
    getList() {
      const data = { ...this.searchRecord, ...this.page }
      removeEmptyString(data)
      page(data).then(result => {
        const { data } = result
        const { totalPages, totalElements, content } = data
        this.tableData = content
        this.page.total = totalElements
        console.log(totalPages) // 页数
      }).catch(e => {

      })
    },
    // 分页相关函数
    pageSizesChange(val) {
      this.page.pageSize = val
      this.getList()
    },
    currentPageChange(val) {
      this.page.currentPage = val
      this.getList()
    },
    query(record) {
      console.log(record)
      this.queryDialog.visible = true
      this.queryRecord = record
    },
    edit(record) {
      this.editDialog.visible = true
      this.editRecord = record
      this.editRecord.password = ''
      this.getRoleList()
      this.editTabsActive = 'first'
    },
    editDialogSave() {
      if (this.editTabsActive === 'first') {
        this.$refs.editDialogForm.validate((valid) => {
          if (valid) {
            removeEmptyString(this.editRecord)
            edit(this.editRecord).then(result => {
              this.editDialog.visible = false
              this.getList()
              Message.success('编辑成功！！！')
            }).catch(e => {

            })
          } else {
            return false
          }
        })
      } else {
        if (this.roleTableSelection.length <= 0) {
          Message.info('请至少选择一个')
          return
        }
        const userId = this.editRecord.userId
        const roleIds = this.roleTableSelection.map(role => role.roleId)
        assignRole(userId, roleIds).then(result => {
          this.editDialog.visible = false
          this.getList()
          Message.success('编辑成功！！！')
        }).catch(e => {

        })
      }
    },
    getRoleList() {
      findAll().then(result => {
        this.roleTableData = result.data
      }).catch(e => {

      })
    },
    tabClick(tab, event) {
      if (this.editTabsActive === 'second') {
        if (this.editRecord.roles === undefined || this.editRecord.roles === null) this.editRecord.roles = []
        this.roleTableSelection = this.editRecord.roles
        this.roleTableSelection.forEach(role => {
          const index = this.roleTableData.findIndex(r => r.roleId === role.roleId)
          this.$refs.roleTable.toggleRowSelection(this.roleTableData[index])
        })
      }
    },
    roleTableSelectionChange(selection) {
      this.roleTableSelection = selection
    },

    remove(record) {
      this.$confirm('确认删除？')
        .then(() => {
          deleteByIds([record.userId]).then(result => {
            this.getList()
            Message.success('删除成功！！！')
          }).catch(e => {

          })
        }).catch(() => {})
    },
    create() {
      this.createDialog.visible = true
    },
    createDialogSave() {
      this.$refs.createDialogForm.validate((valid) => {
        if (valid) {
          removeEmptyString(this.createRecord)
          create(this.createRecord).then(result => {
            this.createDialog.visible = false
            this.getList()
          }).catch(e => {

          })
        } else {
          return false
        }
      })
    },
    bathDelete() {
      if (this.tableSelection.length <= 0) {
        Message.info('请至少选择一个')
        return
      }
      this.$confirm('确认删除？')
        .then(() => {
          const ids = this.tableSelection.map(record => record.userId)
          deleteByIds(ids).then(result => {
            this.getList()
            Message.success('删除成功！！！')
          }).catch(e => {

          })
        }).catch(() => {})
    },
    importData() {

    },
    exportData() {

    },
    templateDown() {

    }
  }
}
</script>

<style scoped>

</style>
